package com.yz.fanrenmianshi.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yz.fanrenmianshi.common.BaseResponse;
import com.yz.fanrenmianshi.common.DeleteRequest;
import com.yz.fanrenmianshi.common.ErrorCode;
import com.yz.fanrenmianshi.common.ResultUtils;
import com.yz.fanrenmianshi.constant.UserConstant;
import com.yz.fanrenmianshi.exception.BusinessException;
import com.yz.fanrenmianshi.exception.ThrowUtils;
import com.yz.fanrenmianshi.model.dto.questionfavour.QuestionFavourAddRequest;
import com.yz.fanrenmianshi.model.dto.questionfavour.QuestionFavourQueryRequest;
import com.yz.fanrenmianshi.model.dto.questionfavour.QuestionIdRequest;
import com.yz.fanrenmianshi.model.entity.QuestionFavour;
import com.yz.fanrenmianshi.model.entity.User;
import com.yz.fanrenmianshi.model.vo.QuestionFavourVO;
import com.yz.fanrenmianshi.service.QuestionFavourService;
import com.yz.fanrenmianshi.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 题目收藏接口
 *
 */
@RestController
@RequestMapping("/questionFavour")
@Slf4j
public class QuestionFavourController {

    @Resource
    private QuestionFavourService questionFavourService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建题目收藏
     *
     * @param questionFavourAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestionFavour(@RequestBody QuestionFavourAddRequest questionFavourAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionFavourAddRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(questionFavourAddRequest.getQuestionId() == null || questionFavourAddRequest.getQuestionId() <= 0, 
                ErrorCode.PARAMS_ERROR, "题目id不能为空");
        
        User loginUser = userService.getLoginUser(request);
        
        // 检查是否已收藏（包括逻辑删除的记录）
        Long questionId = questionFavourAddRequest.getQuestionId();
        Long userId = loginUser.getId();
        QuestionFavour existingDeletedFavour = questionFavourService.listDeletedFavour(questionId, userId);
        
        if (existingDeletedFavour != null) {
            // 存在逻辑删除的记录，恢复该记录
            boolean updateResult = questionFavourService.restoreDeletedFavour(existingDeletedFavour.getId());
            ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "收藏失败");
            return ResultUtils.success(existingDeletedFavour.getId());
        }
        
        // 检查是否已收藏且未删除
        QueryWrapper<QuestionFavour> activeQueryWrapper = new QueryWrapper<>();
        activeQueryWrapper.eq("questionId", questionFavourAddRequest.getQuestionId());
        activeQueryWrapper.eq("userId", loginUser.getId());
        activeQueryWrapper.eq("isDelete", 0);
        QuestionFavour existingActiveFavour = questionFavourService.getOne(activeQueryWrapper);
        
        if (existingActiveFavour != null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "已经收藏过该题目");
        }
        
        // 创建新的收藏记录
        QuestionFavour questionFavour = new QuestionFavour();
        questionFavour.setQuestionId(questionFavourAddRequest.getQuestionId());
        questionFavour.setUserId(loginUser.getId());
        
        // 数据校验
        questionFavourService.validQuestionFavour(questionFavour, true);
        
        // 写入数据库
        boolean result = questionFavourService.save(questionFavour);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        
        // 返回新写入的数据 id
        long newQuestionFavourId = questionFavour.getId();
        return ResultUtils.success(newQuestionFavourId);
    }

    /**
     * 删除题目收藏
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionFavour(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionFavour oldQuestionFavour = questionFavourService.getById(id);
        ThrowUtils.throwIf(oldQuestionFavour == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionFavour.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 逻辑删除
        boolean result = questionFavourService.deleteQuestionFavour(oldQuestionFavour.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据题目id取消收藏（给用户使用）
     *
     * @param questionIdRequest
     * @param request
     * @return
     */
    @PostMapping("/delete/by/question")
    public BaseResponse<Boolean> deleteQuestionFavourByQuestionId(@RequestBody QuestionIdRequest questionIdRequest, HttpServletRequest request) {
        if (questionIdRequest == null || questionIdRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long questionId = questionIdRequest.getQuestionId();
        
        // 查询收藏记录（只查未删除的）
        QueryWrapper<QuestionFavour> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionId", questionId);
        queryWrapper.eq("userId", user.getId());
        queryWrapper.eq("isDelete", 0);
        QuestionFavour questionFavour = questionFavourService.getOne(queryWrapper);
        ThrowUtils.throwIf(questionFavour == null, ErrorCode.NOT_FOUND_ERROR, "未找到收藏记录");
        
        // 逻辑删除
        boolean result = questionFavourService.deleteQuestionFavour(questionFavour.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }



    /**
     * 根据 id 获取题目收藏（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionFavourVO> getQuestionFavourVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        QuestionFavour questionFavour = questionFavourService.getById(id);
        ThrowUtils.throwIf(questionFavour == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(questionFavourService.getQuestionFavourVO(questionFavour, request));
    }

    /**
     * 分页获取题目收藏列表（仅管理员可用）
     *
     * @param questionFavourQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionFavour>> listQuestionFavourByPage(@RequestBody QuestionFavourQueryRequest questionFavourQueryRequest) {
        long current = questionFavourQueryRequest.getCurrent();
        long size = questionFavourQueryRequest.getPageSize();
        // 查询数据库
        Page<QuestionFavour> questionFavourPage = questionFavourService.page(new Page<>(current, size),
                questionFavourService.getQueryWrapper(questionFavourQueryRequest));
        return ResultUtils.success(questionFavourPage);
    }

    /**
     * 分页获取题目收藏列表（封装类）
     *
     * @param questionFavourQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionFavourVO>> listQuestionFavourVOByPage(@RequestBody QuestionFavourQueryRequest questionFavourQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionFavourQueryRequest.getCurrent();
        long size = questionFavourQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionFavour> questionFavourPage = questionFavourService.page(new Page<>(current, size),
                questionFavourService.getQueryWrapper(questionFavourQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionFavourService.getQuestionFavourVOPage(questionFavourPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题目收藏列表
     *
     * @param questionFavourQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionFavourVO>> listMyQuestionFavourVOByPage(@RequestBody QuestionFavourQueryRequest questionFavourQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionFavourQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionFavourQueryRequest.setUserId(loginUser.getId());
        long current = questionFavourQueryRequest.getCurrent();
        long size = questionFavourQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionFavour> questionFavourPage = questionFavourService.page(new Page<>(current, size),
                questionFavourService.getQueryWrapper(questionFavourQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionFavourService.getQuestionFavourVOPage(questionFavourPage, request));
    }
}